import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-user-control',
	templateUrl: './user.component.html',
})
export class UserControlComponent implements OnInit {
	validatorOptions = {
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
//			userNameFrom:{
//				trigger:"change",
//				validators: {
//					notEmpty: {
//						message: '请选择用户'
//					}
//				}
//			},
			lockStatus: {
				validators: {
					notEmpty: {
						message: '请选择用户状态'
					}
				}
			},
			expirationDate:{
				trigger:"change",
				validators: {
					callback:{
						callback:function(value,validator,$field){
	                  		if(value){
//	                  			var temValue = value.substring(0,value.indexOf(' '));
//	                  			var isDate=common.checkDayFormat(temValue);
//								if(!isDate){
//									return{
//										valid:false,
//		                  				message:'到期时间格式不正确'
//									}
//								}else{
		                  			return true;
//		                  		}
	                  		}else{
	                  			return{
									valid:false,
	                  				message:'请选择到期时间'
								}
	                  		}
	                  	}.bind(this)
					}
				}
			}
		}
	}
	tableData:any[] = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	tableSearch:any = {
		searchKey:''
	}
	startTime:string='';
	endTime:string='';
	userList:any; //用户数据
	userId:string = ''; //用户名称
	userName:string = ''; //用户ID
	userControlFrom:any  = {
		id:null,
		userName:'',
		userId:'',
		expirationDate:'',
		lockStatus:'1'
	}
	formType:string = 'new';
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute ) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage||1;
		});
	}
	//擦除用户所选值
	delUserName(){
		this.userName = '';
		this.userId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2').val("");
		$("#select2-userNameSelect2-container").empty();
		$("#select2-userNameSelect2-container").attr("title","");
		$("#select2-userNameSelect2-container").prepend(str);
		this.load();
	}
	//擦除用户所选值
	delUserNameFrom(){
		this.userControlFrom.userName = '';
		this.userControlFrom.userId = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2From').val("");
		$("#select2-userNameSelect2From-container").empty();
		$("#select2-userNameSelect2From-container").attr("title","");
		$("#select2-userNameSelect2From-container").prepend(str);
		this.load();
	}
	//初始化select2 选项
	selectUserName(){
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				$("#userNameSelect2").select2({
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
			    	data : this.userList,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
		        	  	var data = e.params.data;
		        	  	that.userName = data.text;
		        	  	that.userId = data.id;
		        });
			})
		})
	}
	selectUserNameFrom(){
		var that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				$("#userNameSelect2From").select2({
			    	language : "zh-CN",
			    	placeholder :"请选择",
			    	allowClear : true,
			    	data : this.userList,//为Select添加数据
			        templateResult: this.formatRepo
			    }).on ("select2:select", function (e){
		        	  	var data = e.params.data;
		        	  	that.userControlFrom.userName = data.text;
		        	  	that.userControlFrom.userId = data.id;
		        	  	$("#userNameFrom").val(that.userControlFrom.userName).change();
		        });
			})
		})
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//拉取
	initAllUser(){
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("user/getUserList.html",null).subscribe(data=> {
				if(data.success){
					var userList = data.data;
		        	var selectdata = [];
		        	for(var i = 0 ; i < userList.length ; i++) {
		        		var obj = {
		        			id:userList[i].id,
		        			text:userList[i].userName,
		        		}
		        		selectdata[i] = obj;
		        	}
				}
				that.userList = selectdata;
				resolve();
			})
		})
	}
	// 接收子组件传递过来的数据 
	getSelectTableTime(time){
		this.startTime=time.startTime;
		this.endTime=time.endTime;
	} 
	ngOnInit(){
		this.initAllUser().then(()=>{
			this.selectUserName();
			this.selectUserNameFrom();
			this.load();
		});
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			()=>{System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
				$('#expirationDate').datetimepicker({ //时间插件
					format: 'yyyy-mm-dd',
					language: "zh-CN",
					autoclose: true,
					minView: 2
				}).on("changeDate", function(e){
					var date = e.date;
					if(!date){return;}
					var time = common.getTimeDay(date);
					$('#expirationDate').val(time).change();
				});
			});}
		);
	}
	//table刷新
    refresh(){
    	this.load();
    }
	//表格搜索
	table_search(){
		this.curPage = 1;
		this.load();
	}
	//初始化加载list数据
	load(){
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let data = {
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				userId:this.userId,
				startTime:this.startTime,
				endTime:this.endTime,
				searchKey:common.stringTrim(this.tableSearch.searchKey)
			}
		}
		let reqdata = 'gridPager='+JSON.stringify(data);
		this.jsonApiService.http("apiUserConfig/queryUserConfig.html", reqdata).subscribe(data => {
			if(data.isSuccess){
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			}else{
				this.jsonApiService.message(data.message);
			}
		})
	}
	//删除
	delRow(row){
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			this.jsonApiService.http_obj("apiUserConfig/deleteUserConfig.html",{id:row.id}).subscribe(data=>{
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
				}
			})
		})
	}
	
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	/*
	 * 新增
	 */
	table_add(modal){
		this.modalClose(modal);
		this.formType = 'new';
		modal.show();
	}
	/*
	 * 状态change回调
	 */
	lockStatusChange(val){
		this.userControlFrom.lockStatus = val;
	}
	/*
	 * 编辑
	 */
	editRow(row,modal){
		this.formType = 'updata';
		modal.show();
		this.userControlFrom.id = row.id;
		this.jsonApiService.http_obj("apiUserConfig/queryUserConfigById.html",{id:row.id}).subscribe(data=>{
			if(data.data){
				for(let item in this.userControlFrom){
					this.userControlFrom[item] = data.data[item];
					if(item == 'userId'){
						$('#userNameSelect2From').val(data.data.userId).trigger('change');
					}
					if(item == 'lockStatus'){
						this.userControlFrom[item] = data.data[item]+'';
					}
				}
			}
		})
	}
	/*
	 * 关闭弹窗
	 */
	modalClose(modal){
		modal.hide();
		$("#userControlFrom").data('bootstrapValidator').resetForm();
		this.userControlFrom.id = '';
		this.userControlFrom.userName = '';
		this.userControlFrom.userId = '';
		this.userControlFrom.expirationDate = '';
		this.userControlFrom.lockStatus = '1';
		$('#expirationDate').val('');
//		$('#userNameSelect2From').val('').trigger('change');
		this.delUserNameFrom();
	}
	/*
	 * form提交
	 */
	userControlSubmit(modal){
		if(!this.userControlFrom.userName&&this.formType == 'new'){
			this.jsonApiService.message('请选择用户');
			return;
		}
		this.userControlFrom.expirationDate = $('#expirationDate').val();
		$('#userControlFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#userControlFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
			let url;
			if(this.formType == 'new'){
				url = "apiUserConfig/addUserConfig.html";
			}else if(this.formType == 'updata'){
				url = "apiUserConfig/updateUserConfig.html";
			}
			this.jsonApiService.http_obj(url,this.userControlFrom).subscribe(data=> {
				this.jsonApiService.message(data.message);
				if(data.success){
					this.load();
					this.modalClose(modal);
				}
			})
		}
	}
}